<template>
    <h2>人员管理</h2>
    <search-form :fields="searchFields" :initial-form="initialSearchValues" :inline="true" :label-width="'80px'"
        :show-reset="true" @search="handleSearch" @reset="handleReset">
        <template #extra-buttons>
            <el-button @click="handleExport">导出Excel</el-button>
            <el-button type="success" @click="handleCreate">新增用户</el-button>
        </template>
    </search-form>

    <person-list :items="personStore.items" @edit="handleEdit" @delete="handleDelete" />

    <div class="pagination">
        <el-pagination v-model:current-page="personStore.pagination.page"
            v-model:page-size="personStore.pagination.size" :page-sizes="[10, 20, 50]" :size="size" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="personStore.pagination.total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

</template>

<script setup lang="ts">
import type { ComponentSize } from 'element-plus';
import { onMounted, ref } from 'vue';
import { usePersonStore } from '../../stores/person-store';
import type { Person } from "../../types/person";
import PersonList from "./PersonList.vue";
import SearchForm from "../../components/SearchForm.vue";

const size = ref<ComponentSize>('small')
const personStore = usePersonStore()

onMounted(() => {
    personStore.fetchItems()
})

const handleSearch = () => {
    // TO-DO
}

const handleReset = () => {
    // TO-DO
}

const handleCreate = (row: Person) => {
    // TO-DO
}

const handleEdit = (row: Person) => {
    personStore.updateItem(row)
}

const handleDelete = (row: Person) => {
    if (row.id === undefined) {
        throw new Error('id')
    }
    personStore.deleteItem(row.id)
}


const handleSizeChange = (val: number) => {
    personStore.pagination.size = val;
    personStore.fetchItems();
}

const handleCurrentChange = (val: number) => {
    personStore.pagination.page = val;
    personStore.fetchItems();
}

</script>

<style scoped>
.pagination {
    margin-top: 10px;
}
</style>